package com.stt.experiment.trynetty.buffer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Setter
@Getter
@ToString(callSuper = true)
public class RequestBuffer extends AbstractRequestBuffer {

    private static final long serialVersionUID = 5080154055299081676L;

    private Long userId; // 用户id
    private Channel channel; // 请求连接管道

    public RequestBuffer() {}

    public RequestBuffer(Long userId, String module, String cmd, JSONObject data) {
        this.userId = userId;
        this.module = module;
        this.cmd = cmd;
        this.data = data;
    }

    public RequestBuffer(Channel channel, String requestContent) {
        JSONObject json = JSON.parseObject(requestContent);
        this.channel = channel;
        this.module = json.getString("module");
        this.cmd = json.getString("cmd");
        this.data = json.getJSONObject("data");
        this.userId = json.getLong("userId");
    }

    public RequestBuffer(Channel channel, Long userId, String module, String cmd, JSONObject data) {
        this.channel = channel;
        this.module = module;
        this.cmd = cmd;
        this.data = data;
        this.userId = userId;
    }

    /**
     * 直接回复消息
     * @param buffer 回复内容
     */
    public void reply(ResponseBuffer buffer) {
        this.channel.writeAndFlush(new TextWebSocketFrame(buffer.toJsonString()));
    }
}
